/****************************************************************************** 
 * @Title: StrUtil.java 
 * @author Dafei 
 * Create Date : 2013-4-17 
 * JDK version used:      JDK1.7  
 * @Version : V1.0 
 *  @Description: TODO 
 *  
 * History : 
 * All rights reserved 
 ******************************************************************************/
package com.winstar.utils;

import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 字符串相关工具类,提供字符串处理函数
 * 
 */

/**
 * @author 409147
 *
 */
public class StrUtil {
	
	
	/**
	 * 把字符串通过两次分割,得到键值对Map,
	 * 如查询参数a=aa&b=bb&c=cc&d=dd:,或window环境变量a=aa;b=bb;c=cc;d=dd:等
	 * 
	 * @param str
	 *            要分析的字符串
	 * @param split1
	 *            第一级分割
	 * @param split2
	 *            第二级分割
	 * @return
	 */
	public static Map<String, String> parseToMap(String str, String split1,
			String split2) {
		Map<String, String> map = new TreeMap<String, String>();// 结果变量
		/*
		 * 参数检查
		 */
		/*
		 * if (split1 == null || (split1 = split1.trim()).length() == 0) {
		 * return map; }
		 */
		if (split2 == null || (split2 = split2.trim()).length() == 0) {
			return map;
		}
		if (str == null || (str = str.trim()).length() == 0
				|| str.indexOf(split2) == -1) {
			return map;
		}
		// 第一次分解
		String[] params = str.split(split1);
		// 第二次分解
		for (int i = 0; params != null && i < params.length; i++) {
			if (params[i] == null
					|| (params[i] = params[i].trim()).length() == 0) {
				continue;
			}
			String[] keyValue = params[i].split(split2);
			if (keyValue.length != 2) {
				continue;
			}
			String key = keyValue[0].trim();
			String value = keyValue[1].trim();
			map.put(key, value);
		}
		return map;
	}

	/**
	 * 解析HTTP查询参数,以Map方式返回
	 * 
	 * @param queryString
	 *            查询字符串,如:a=aa&b=bb
	 * @return 以Map方式返回参数集合
	 */
	public static Map<String, String> parseQueryString(String queryString) {
		Map<String, String> map = new TreeMap<String, String>();// 结果对象
		if (queryString == null
				|| (queryString = queryString.trim()).length() == 0) {// 参数为空返回空Map
			return map;
		}
		if (queryString.startsWith("?")) {// 把查询参数前面的?去掉
			queryString.replaceFirst("?", "");
		}
		queryString = queryString.toLowerCase();// 把字符串转成小写字母
		String[] params = queryString.split("&");// 先用'&'符号第一次分解
		for (int i = 0; params != null && i < params.length; i++) {
			String[] keyValue = params[i].split("=");// 用'='符号第二次分解
			if (keyValue == null || keyValue.length != 2) {// 如果拆分结果不是预期的,丢弃该条参数
				continue;
			}
			String key = keyValue[0];
			String value = keyValue[1];
			map.put(key, value);
		}// end of for(int i=0;params!=null&&i<params.length;i++)
		return map;
	}

    /**
     * 字符串转为小写字符
     * @return 
     */
    public static String stringToLowerCase(String a) {

        String str = a;
        str = str.toLowerCase();
        return str;
//        System.out.println(str);
    }
    
	/**
	 * 转成int型
	 * 
	 * @param str
	 *            输入字符串
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static int parseInt(String str, int defaultValue) {
		if (str == null || (str = str.trim()).length() == 0) {
			return defaultValue;
		}
		int intValue = defaultValue;
		try {
			intValue = Integer.parseInt(str);
			return intValue;
		} catch (NumberFormatException e) {
			return defaultValue;
		}
	}
	
	/**
	 * 转成String型
	 * 
	 * @param str
	 *            输入字符串
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static String parseString(String str, String defaultValue) {
		if (str == null || (str = str.trim()).length() == 0) {
			return defaultValue;
		}
		return str;
	}

	/**
	 * 转成double型
	 * 
	 * @param str
	 *            输入字符串
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static double parseDouble(String str, double defaultValue) {
		if (str == null || (str = str.trim()).length() == 0) {
			return defaultValue;
		}
		double value = defaultValue;
		try {
			value = Double.parseDouble(str);
			return value;
		} catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	/**
	 * 转成float型
	 * 
	 * @param str
	 *            输入字符串
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static float parseFloat(String str, float defaultValue) {
		if (str == null || (str = str.trim()).length() == 0) {
			return defaultValue;
		}
		float value = defaultValue;
		try {
			value = Float.parseFloat(str);
			return value;
		} catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	/**
	 * 转成long型
	 * 
	 * @param str
	 *            输入字符串
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static long parseLong(String str, long defaultValue) {
		if (str == null || (str = str.trim()).length() == 0) {
			return defaultValue;
		}
		long longValue = defaultValue;
		try {
			longValue = Long.parseLong(str);
			return longValue;
		} catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	/**
	 * 去头尾空格方法,如果为空,取默认值
	 * 
	 * @param str
	 * @param valueIfEmpty
	 *            为空时返回该值
	 * @return
	 */
	public static String trimToDefault(String str, String valueIfEmpty) {
		str = StringUtils.trimToNull(str);
		if (str == null || str == "") {
			str = valueIfEmpty;
		}
		return str;
	}
	
	/**
	 * 检测邮箱格式正确性
	 * @Function: changeMail
	 * @Description: 测邮箱格式正确性
	 * @param mail 测试邮箱地址
	 * @return value description
	 * @exception/throws  description
	 */
	public static boolean changeMail(String mail) {
		//Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
		Pattern p = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$");
		Matcher m = p.matcher(mail);
	    boolean b = m.matches();
		return b;
    }
	
	/**
	 * 随机生成6位数
	 * @Function:geRandomt
	 * @Description:随机生成6位数
	 * @return 6位数
	 * @exception/throws  description
	 */
	public static int getRandomNum(int dig) {
		int[] array = {1,2,3,4,5,6,7,8,9};
		Random rand = new Random();
		for (int i = 9; i > 1; i--) {
		    int index = rand.nextInt(i);
		    int tmp = array[index];
		    array[index] = array[i - 1];
		    array[i - 1] = tmp;
		}
		int result = 0;
		for(int i = 0; i < dig; i++) {
			result = result * 10 + array[i];
		}
		return result;
	}
	
	/**
	 * 判断字符串是否为空  null也视为空
	 * @param input
	 * @return 为空返回true 否则返回false
	 */
	public static boolean IsNull(String input){
		if(input==null || input.length()<=0 || input.equalsIgnoreCase("null")){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 校验密码：字母和数字组合，长度6-20
	 * @param str
	 * @return
	 */
	public static boolean validatePwd(String str) {
		Pattern pat = Pattern.compile("[\\da-zA-Z]{6,20}");
	     Pattern patno = Pattern.compile(".*\\d.*");
	     Pattern paten = Pattern.compile(".*[a-zA-Z].*");
	     Matcher mat = pat.matcher(str);
	     Matcher matno = patno.matcher(str);
	     Matcher maten = paten.matcher(str);
	     if(matno.matches()&& maten.matches() && mat.matches()){
	         return true;
	     }
	     
	     return false;
	}

	/**
	 * 校验手机号：11位纯数字
	 * @param str
	 * @return
	 */
	public static boolean validatePhone(String str) {
		Pattern pat = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,2,3,5-9]))\\d{8}$");
		Matcher mat = pat.matcher(str);
		if( mat.matches()){
			return true;
		}
		return false;
	}
	
	 

	/**
	 * 判断是否是正整数
	 * @param str
	 * @return 是整数返回true 否则返回false
	 */
	public static boolean isNumeric(String str) {
		if(IsNull(str)){
			return false;
		}
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 判断是否是整数（包含正整数、负整数）
	 * @param str
	 * @return
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	

	public static String encode(String str) throws UnsupportedEncodingException {
		return new String(str.getBytes("ISO8859-1"),"GBK");
	}
	
	/**
	 * 判断是否为手机
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((13[0-9])|177|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
		}
	/**
	 * 判断是否为 email
	 * @param email
	 * @return
	 */
	public static boolean isEmailNO(String email) {
//		Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
		Pattern p = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
		Matcher m = p.matcher(email);
		return m.matches();
	}
	
	/**
	 * @param dataAll 所有数据
	 * @param skip 从第几个开始取数
	 * @param itmeCount 总共去几条数据
	 * @return
	 */
	public static List getRandInList(List dataAll,int skip,int itmeCount){
		return 	dataAll.subList(skip, skip+itmeCount);
	}
	/**
	 * 获取json乱码
	 * @param content
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getUtf(String content){
		try {
			return new String(content.getBytes("ISO-8859-1"),"UTF-8");
		} catch (Exception e) {
			return content;
		}
	}
	

	/**
	 * URL Encode
	 * @param content
	 * @return
	 */
	public static String getUrlCode(String content) {
		try {
			return URLEncoder.encode(content,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			return content;
		}
	}
	
	
	/**
	 * 时间戳转化为Sting或Date
	 * @param aa
	 * @return
	 * @throws ParseException
	 */
	public static String getDateStamp(String aa) throws ParseException{
		//时间戳转化为Sting或Date
		SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
		 Long time=new Long(aa);
		 String d = format.format(time);
		 Date date=format.parse(d);
//		 System.out.println("Format To String(Date):"+d);
//		 System.out.println("Format To Date:"+date);
		 return d;
	}
	/**
	 * 转化为时间戳
	 * @param sdf
	 * @return
	 * @throws ParseException
	 */
	public static long getStampDate(String sdf) throws ParseException{
		//Date或者String转化为时间戳
		 SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
//		 String time="1970-01-06 11:45:55";
		 Date date = format.parse(sdf);
//		 System.out.print("Format To times:"+date.getTime());
		 return date.getTime();
	}

	/**
	 * 转化为时间戳
	 * @param sdf
	 * @return
	 * @throws ParseException
	 */
	public static long getStampDate2(String sdf) {
		//Date或者String转化为时间戳
		SimpleDateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss" );
//		 String time="1970-01-06 11:45:55";
		Date date = new Date();
		try {
			date = format.parse(sdf);
		}catch (Exception e){
			System.out.println("时间转换异常："+e);
		}
//		 System.out.print("Format To times:"+date.getTime());
		return date.getTime();
	}
	/**
	 * list按照id排序
	 * @param listAll
	 * 0降序
	 * 1升序
	 */
    public static void getsort(List<HashMap<String, String>> listAll,int a) {
    	 
        Collections.sort(listAll, new Comparator<Map>() {
 
            public int compare(Map o1, Map o2) {
 
                Integer a = (Integer) o1.get("id");
                Integer b = (Integer) o2.get("id");
 
                // 升序
                //return a.compareTo(b);
                // 降序
//                 return b.compareTo(a);
                 
                 if(a == 0){
                	 return b.compareTo(a);
                 }else{
                	 return b.compareTo(b);
                 }
                 
                 
            }
        });
    }
    
    /**
     * 获取文件扩展名
     * @param filename
     * @return
     */
    public static String getSuffix(String filename){
    	String suffix="";
    	if(!IsNull(filename) && filename.lastIndexOf(".")>=0){
    		suffix = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();
    	}
    	
    	return suffix;
    }
    
    

    public static final String numberChar = "0123456789"; 
    
    /**
     * 返回固定长度的随机字符串
     * @param length
     * @return
     */
    public static String generateRandomString(int length) {
            StringBuffer sb = new StringBuffer(); 
            Random random = new Random(); 
            for (int i = 0; i < length; i++) { 
                    sb.append(numberChar.charAt(random.nextInt(numberChar.length()))); 
            } 
            return sb.toString(); 
    } 
    
    /**
     * 生成随机UUID,并去掉中间的分隔符 -
     * @return
     */
    public static String getUUID(){
    	String uuidStr=UUID.randomUUID()+"";
    	return uuidStr.replaceAll("-", "");
    }

    
    
    
    
    /**
     * 通过URl获取链接大小
     * @param aa
     * @return
     * @throws IOException
     */
    public static String getSize(String aa) throws IOException{
        URL url = new URL(aa);
        URLConnection uc = url.openConnection();
//        System.out.println("文件大小："+(uc.getContentLength()/1024)+"KB");
//        return (uc.getContentLength()/1024)+"KB";
//          return (uc.getContentLength()/1048576)+"M";
  
        double a = uc.getContentLength()/1024;
        double b = a/1024;
        String c = new java.text.DecimalFormat("#.00").format(b); //保留两位小数，四舍五入
//        return c+"M";
        return c;
        
//        String fileName = uc.getHeaderField(6);
//        fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
//        System.out.println("文件名为："+fileName);
        
        
        /*String path = "D:"+File.separator+fileName;
        FileOutputStream os = new FileOutputStream(path);
        InputStream is = (InputStream) uc.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len=is.read(b))!=-1){
            os.write(b,0,len);
        }
        os.close();
        is.close();
        System.out.println("下载成功,文件保存在："+path);*/
    }
    
    /**
     * 生成6位数的验证码
     * @return  string
     * */
    public static String getSix(){  
        Random rad=new Random();  
          
        String result  = rad.nextInt(1000000) +"";  
          
        if(result.length()!=6){  
            return getSix();  
        }  
        return result;  
    }  
    
    
    /**
     * 接收到布尔类型的数据，转换为int
     * 1：true；0：false
     * @return
     */
    public static String booleanParamFormat(String input) {
    	if(IsNull(input)){
    		return "0";
    	}
    	if(input.equalsIgnoreCase("true")){
    		return "1";
    	}else{
    		return "0";
    	}
	}

	/**
	 * 获取ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 校验字符串参数非空
	 *
	 * @param args 被检验的字符串参数
	 * @return true or false
	 */
	public static boolean checkStrsNull(Object...args){
		for (Object para:args
				) {
			if(org.springframework.util.StringUtils.isEmpty(para)){
				return true;
			}
		}
		return false;
	}

	/**
	 * 校验字符串参数包含
	 *
	 * @param checkedStrs 被检验的字符串
	 * @param containStr 被包含的字符串
	 * @return true or false
	 */
	public static boolean checkStrsContain(String checkedStrs,String...containStr){
		for (String para:containStr
				) {
			if(checkedStrs.contains(para)){
				return true;
			}
		}
		return false;
	}

	/**
	 * BASE64加密
	 *
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptBASE64(String key){
		byte[] bt = key.getBytes();
		return (new BASE64Encoder()).encodeBuffer(bt);
	}

	/**
	 * BASE64解密
	 *
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptBASE64(String key){
		byte[] bt;
		try {
			bt = (new BASE64Decoder()).decodeBuffer(key);
			return new String(bt, "GB2312");
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}


	/*public static void main(String[] args) {


		System.out.println(validatePhone("14452036598"));

	}*/

}
